import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '../stores/user'
import Layout from '../views/Layout.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('../views/Home.vue'),
      },
      {
        path: 'organization',
        name: '组织管理',
        component: () => import('../views/organization/Organization.vue'),
        children: [
          { path: 'users', name: '用户管理', component: () => import('../views/organization/Users.vue') },
          { path: 'roles', name: '角色管理', component: () => import('../views/organization/Roles.vue') },
          { path: 'menus', name: '菜单管理', component: () => import('../views/organization/Menus.vue') },
        ]
      },
      {
        path: 'tools',
        name: '工具管理',
        component: () => import('../views/tools/Tools.vue'),
        children: [
          { path: 'graphql', name: 'GraphQL', component: () => import('../views/tools/Graphql.vue') },
          { path: 'realtime', name: '实时通讯', component: () => import('../views/tools/Realtime.vue') },
        ]
      },
      {
        path: 'my',
        name: '我的',
        component: () => import('../views/my/My.vue'),
        children: [
          { path: 'profile', name: '我的资料', component: () => import('../views/my/Profile.vue') },
          { path: 'album', name: '我的相册', component: () => import('../views/my/Album.vue') },
          { path: 'music', name: '我的音乐', component: () => import('../views/my/Music.vue') },
          { path: 'video', name: '我的视频', component: () => import('../views/my/Video.vue') },
          { path: 'books', name: '我的图书', component: () => import('../views/my/Books.vue') },
        ]
      },
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/',
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next('/login')
  } else if (to.path === '/login' && userStore.isLoggedIn) {
    next('/')
  } else {
    next()
  }
})

export default router
